﻿using KouDai.Phone.Helper;
using KouDai.Phone.Parsers;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace KouDai.Phone.Engine
{
    public class HttpContentEngine : IHttpEngine
    {
        public async Task RequestAsync(CommunicationData cdata)
        {
            await RequestAsync(cdata, CancellationToken.None);
        }

        public async Task RequestAsync(CommunicationData cdata, CancellationToken cancellationToken)
        {
            SendData sendData = cdata.SendData;
            BaseParser parser = cdata.Parser;
            BackData backData = cdata.BackData;

            //post params
            Dictionary<string, object> bodyParams = sendData.Body;
            EncryptType encryptType = sendData.EncryptType;
            Dictionary<string, object> headerParams = sendData.Headers;
            string data = BuildParams(encryptType, headerParams, bodyParams);
            //url
            string tailUrl = sendData.TailUrl;
            //method
            string method = sendData.Method.ToString();
            //request bytes
            HttpConnection conn = new HttpConnection();
            Task<byte[]> byteTask = conn.RequestAsync(Constants.Host + tailUrl, method, data, cancellationToken);
            await byteTask.ConfigureAwait(false);
            byte[] resBytes = await byteTask;
            //get json str
            string json = Encoding.UTF8.GetString(resBytes, 0, resBytes.Length);
            //parser
            if (parser != null)
            {
                parser.ParseJson(json, backData);
                backData.IsSuccess = true;
                backData.Msg = "Get Data Success.";
            }
            else
            {
                backData.IsSuccess = false;
                backData.Msg = "Parser is null.";
            }
        }

        /// <summary>
        /// 拼接请求的parameters
        /// </summary>
        /// <param name="encryptType"></param>
        /// <param name="body"></param>
        /// <returns></returns>
        private string BuildParams(EncryptType encryptType, Dictionary<string, object> headerParams, Dictionary<string, object> bodyParams)
        {
            return encryptType == EncryptType.AES ? ParamHelper.EncryptParam(headerParams, bodyParams) : ParamHelper.BuildParas(bodyParams);
        }
    }
}
